package com.bianguo.android.tencentpushdemo.view.activity;

import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;

import com.bianguo.android.tencentpushdemo.R;
import com.bianguo.android.tencentpushdemo.utils.MyLog;
import com.bianguo.android.tencentpushdemo.view.widget.ProgressView;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class RecordVideoActivity extends BaseActivity implements View.OnTouchListener, SurfaceHolder.Callback {

    @BindView(R.id.record_video_surface)
    SurfaceView mSurfaceView;
    @BindView(R.id.record_video_progress)
    ProgressView mProgressView;
    @BindView(R.id.record_video_start)
    TextView startTv;

    private float pressY;
    private int recordTime;
    private Timer mTimer;
    private SurfaceHolder surfaceHolder;
    private MediaRecorder mRecorder;

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    MyLog.myLog("recordTime = " + recordTime);
                    mProgressView.setProgress(recordTime);
                    break;
                case 1:
                    recordTime = 0;
                    if (mTimer != null) {
                        mTimer.cancel();
                        mTimer = null;
                    }
                    break;
            }
        }
    };

    @Override
    public int layoutId() {
        return R.layout.activity_record_video;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        mProgressView.setMax(10);
        startTv.setOnTouchListener(this);
    }

    @Override
    public void initData() {
        SurfaceHolder holder = mSurfaceView.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @OnClick({R.id.record_video_start})
    public void onClick(View view){
        switch (view.getId()) {
            case R.id.record_video_start:
                break;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                pressY = event.getRawY();
                startTimer();
                startRecord();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                recordTime = 0;
                if (mTimer != null) {
                    mTimer.cancel();
                    mTimer = null;
                }
                startRecord();
                break;
        }
        return true;
    }

    private void startRecord(){
        mRecorder = new MediaRecorder();// 创建mediarecorder对象
        // 设置录制视频源为Camera(相机)
        mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mRecorder.setOrientationHint(90);
        // 设置录制完成后视频的封装格式THREE_GPP为3gp.MPEG_4为mp4
        mRecorder
                .setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        // 这两项需要放在setOutputFormat之后
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
        // 设置视频录制的分辨率。必须放在设置编码和格式的后面，否则报错
        mRecorder.setVideoSize(640, 480);
        // 设置录制的视频帧率。必须放在设置编码和格式的后面，否则报错
//        mRecorder.setVideoFrameRate(20);
        mRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        // 设置视频文件输出的路径
        mRecorder.setOutputFile("/sdcard/video" + System.currentTimeMillis() + ".mp4");
        try {
            // 准备录制
            mRecorder.prepare();
            // 开始录制
            mRecorder.start();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void stopRecord(){
        if (mRecorder != null) {
            // 停止录制
            mRecorder.stop();
            // 释放资源
            mRecorder.release();
            mRecorder = null;
        }
    }

    private void startTimer(){
        if (mTimer == null) {
            mTimer = new Timer();
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    recordTime++;
                    if (recordTime >= 10) {
                        mHandler.sendEmptyMessage(1);
                    } else {
                        mHandler.sendEmptyMessage(0);
                    }
                }
            }, 0, 1000);
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        stopRecord();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // 将holder，这个holder为开始在oncreat里面取得的holder，将它赋给surfaceHolder
        surfaceHolder = holder;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // 将holder，这个holder为开始在oncreat里面取得的holder，将它赋给surfaceHolder
        surfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mSurfaceView = null;
        surfaceHolder = null;
        mRecorder = null;
    }
}
